package com.learn.micro_mall.domain.service.category;

import com.learn.micro_mall.domain.entity.category.CategoryEntity;
import com.learn.micro_mall.domain.vo.category.CategoryId;
import com.learn.micro_mall.repository.category.CategoryRepository;
import com.learn.micro_mall.service.request.category.CategoryCreateRequest;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class ValidatorCategoryDomainService {

    @Resource
    private CategoryRepository categoryRepository;

    public void validatorParentCategoryExist(String parentCategoryId) throws Exception {
        if(parentCategoryId == null){
            log.info("ValidatorCategoryDomainService.validatorParentCategoryExist 该商品分类无上级分类,无需校验");
            return;
        }
        CategoryId categoryId = CategoryId.builder().categoryId(parentCategoryId).build();
        CategoryEntity categoryEntity = categoryRepository.getByCategoryId(categoryId);
        if(categoryEntity == null){
            throw new Exception("不存在该上级分类");
        }
    }

    public void validatorTheSameLevelCategoryNoExist(CategoryCreateRequest request) throws Exception {
       String categoryId = request.getParentCategoryId() != null ? request.getParentCategoryId() + request.getCategoryName() : request.getCategoryName();
       CategoryEntity categoryEntity = categoryRepository.getByCategoryId(CategoryId.builder().categoryId(categoryId).build());
       if(categoryEntity != null){
           throw new Exception("在该层级下已经存在同样名字的商品分类,请修改名字后重新创建");
       }
    }

    public void validatorCategoryExist(String categoryId) throws Exception {
        CategoryEntity categoryEntity = categoryRepository.getByCategoryId(CategoryId.builder().categoryId(categoryId).build());
        if(categoryEntity == null){
            throw new Exception("不存在该商品分类");
        }
    }
}
